跳到主要内容

BM15 删除有序链表中重复的元素-I

https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79

标准解法

func deleteDuplicates( head *ListNode ) *ListNode {
if head == nil { // 注意边界条件的判断
return head
}
o := head
for head.Next != nil {
if head.Val == head.Next.Val {
head.Next = head.Next.Next
} else {
head = head.Next
}
}
return o
}

23/5/10 暴力解法

用时 8分钟

func deleteDuplicates(head *ListNode) *ListNode {
m := make(map[int]struct{})
dummy := new(ListNode)
pre := dummy
for head != nil {
if _, ok := m[head.Val]; !ok {
m[head.Val] = struct{}{}
pre.Next = &ListNode{Val: head.Val}
pre = pre.Next
}
head = head.Next
}
return dummy.Next
}

暴力解法非常简单,使用 map 来记录已经出现过的值,如果出现过就不再添加,否则就添加到链表中